defer Statements

Sometimes you create something that needs to be destroyed at the end of the scope. Rather than manually putting the code that handles this destruction at the end of the scope, you can instead use defer. This means that you can write some code in the middle of a scope and slap defer in front of it, making it actually happen at the end of the scope.

read_file :: proc() {
  f, err := os.open("my_file.txt")

  if err != os.ERROR_NONE {
    // handle error
  }

  defer os.close(f)

  // Put code here that uses `f`
  // to read data from file.

  // os.close(f) is run at the end of
  // the procedure.
}

defer statement is happened after returning from procedure.

Date: 2026-07-17 Fri